package com.kfm.spring.test;

import com.kfm.spring.model.Account;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:application.xml"})
public class Demo {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Test
    public void bean(){
        System.out.println(jdbcTemplate);
    }

    @Test
    public void insert(){
        String sql = "insert into account(uid, money) values(?, ?)";
        int row = jdbcTemplate.update(sql, 1, 999.99);
        Assert.assertEquals(1, row);
    }

    @Test
    public void update(){
        String sql = "update account set money = ? where id = ?";
        int row = jdbcTemplate.update(sql, 888.88, 8);
        Assert.assertEquals(1, row);
    }

    @Test
    public void findById(){
        String sql = "select * from account where id = ?";
//        Map<String, Object> result = jdbcTemplate.queryForMap(sql, 8);
//
//        Set<String> keys = result.keySet();
//
//        for(String key : keys){
//            System.out.println(key + " : " + result.get(key) );
//        }

        Account account = jdbcTemplate.queryForObject(sql, new RowMapper<Account>() {
            @Override
            public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
                Account account = new Account();
                account.setId(rs.getInt("id"));
                account.setUid(rs.getInt("uid"));
                account.setMoney(rs.getDouble("money"));
                return account;
            }
        }, 8);
//        jdbcTemplate.query(sql, (rs, rowNum) -> {
//            Account account = new Account();
//            account.setId(rs.getInt("id"));
//            account.setUid(rs.getInt("uid"));
//            account.setMoney(rs.getDouble("money"));
//            return account;
//        }, 8);
        System.out.println(account);
    }

    @Test
    public void findAll(){
        String sql = "select * from account";
        List<Account> query = jdbcTemplate.query(sql, (rs, rowNum) -> {
            Account account = new Account();
            account.setId(rs.getInt("id"));
            account.setUid(rs.getInt("uid"));
            account.setMoney(rs.getDouble("money"));
            return account;
        });

        for (Account account : query) {
            System.out.println(account);
        }
    }
}
